package com.example.proxy.cglib;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * <p> CGLib 代理 </p>
 *
 * @author Chris
 * @since 2022/11/29 14:01
 */
public class CglibProxy implements MethodInterceptor {

    private UserServiceImpl userService;

    public UserServiceImpl newInstance(final UserServiceImpl userService) {
        this.userService = userService;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.userService.getClass());
        enhancer.setCallback(this);
        return (UserServiceImpl) enhancer.create();
    }

    public UserService newInstance(Class<?> clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return (UserService) enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("代理前");
        if (obj.getClass().isInterface()) {
            System.out.println("代理后");
            return null;
        }
        final Object invoke = methodProxy.invokeSuper(obj, args);
        System.out.println("代理后");
        return invoke;
    }

}